package com.example.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @Classname RedisConfig
 * @Description TODO RedisTemplate注入bean对象
 * @Version 1.0.0
 * @Date 2023/1/26 13:23
 * @Created by wlh12
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 连接“工厂”
        template.setConnectionFactory(redisConnectionFactory);
        // -----序列化-----
        // string的key采用StringRedisSerializer的序列化
        template.setKeySerializer(RedisSerializer.string());
        // string的value采用Jackson的序列化
        template.setValueSerializer(redisSerializer);
        // hash的key采用StringRedisSerializer的序列化
        template.setHashKeySerializer(RedisSerializer.string());
        // hash的value采用Jackson的序列化
        template.setHashValueSerializer(redisSerializer);
        template.afterPropertiesSet();// 把配置都放进去
        return template;
    }
}
